<?php
	require_once('includes/bootstrap.php');
	
	if (!empty($_POST))
	{
		foreach ($_POST['commande'] as $code => $quantity)
		{
			if ($quantity == 0)
				unset($_SESSION['commande'][$code]);
			else if (isset($_SESSION['commande'][$code]))
				$_SESSION['commande'][$code]['quantity'] = $quantity;
		}
		
		if (isset($_POST['continuer']))
		{
			$_SESSION['commande_validée'] = true;
			
			if (empty($_SESSION['client']))
				header('location: ' . APPLICATION_URL . 'register.php');
			else
				header('location: ' . APPLICATION_URL . 'confirm_order.php');
			
			exit;
		}
	}
?>

<html>
	<head>
		<?php include_once('includes/head.php'); ?>
	</head>

	<body>

		<?php include_once('includes/header.php'); ?>
		
		<h2>Mon panier</h2>
		
		<?php
			if (empty($_SESSION['commande']))
			{
				echo '<br /><br /><p style="text-align: center; font-style: italic">Votre panier est vide</p>';
			}
			else
			{
		?>
		
		<form method="POST" id="basket">
			
			<table>
				<tr>
					<th>Article</th>
					<th style="width: 100px;">Quantité</th>
					<th style="width: 75px;">Prix</th>
				</tr>
				<?php
					$itemsCount = 0;
					$price = 0;
				
					foreach ($_SESSION['commande'] as $item)
					{
						echo '<tr>';
						echo '	<td>' . $item['name'] . '</td>';
						echo '	<td class="center"><input type="text" name="commande[' . $item['code'] . ']" value="' . $item['quantity'] . '" /></td>';
						echo '	<td class="center">' . $item['quantity'] * $item['price'] . ' €</td>';
						echo '</tr>';
						
						$itemsCount += $item['quantity'];
						$price += $item['quantity'] * $item['price'];
					}
				?>
				<tr style="background: lightgrey">
					<td>Total</td>
					<td class="center"><?= $itemsCount ?></td>
					<td class="center"><?= $price ?> €</td>
				</tr>
				<tr>
					<td colspan="3">&nbsp;</td>
				</tr>
				<tr>
					<td colspan="3" style="text-align: right">
						<button type="submit" name="recalculer">Recalculer les montants</button>
						<button type="submit" name="continuer">Continuer</button>
					</td>
				</tr>
			</table>
			
		</form>
		
		<script type="text/javascript">
			$("input:text, input:password, textarea").addClass("ui-corner-all");
			
			$('form table').addClass('ui-widget ui-widget-content ui-corner-all');

			$("button").button();
		</script>
		
		<?php } ?>

	</body>

</html>
